package com.tanhua.server.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class MyControllerLog {
    //保证同步安全性（可以不加）
    private ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    //定义一个切入点
    @Pointcut("execution(* com.tanhua.server.controller..*.*(..))")
    public void logPointCut() {
    }

    //在方法之前切入内容（打印日志）
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        threadLocal.set(new Date().getTime());
        //记录当前时间
        log.debug("访问时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //从RequestContextHolder中获取servlet请求属性
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //从servletRequestAttributes获取HttpServletRequest对象
        HttpServletRequest servletRequest = servletRequestAttributes.getRequest();
        //获取请求路径
        //log.debug("请求路径为：" + servletRequest.getRequestURL());
        //获取请求方式
        log.debug("请求方式为:" + servletRequest.getMethod());
        //获取请求参数
        log.debug("请求参数为：" + Arrays.toString(joinPoint.getArgs()));
    }

    //在方法返回值之后切入内容（获得返回值）
    @AfterReturning(returning = "result", pointcut = "logPointCut()")
    public void doAfterReturning(Object result) throws Throwable {
        log.debug("方法返回值：" + result);
        log.debug("耗时：" + (new Date().getTime() - threadLocal.get()) + "毫秒");
        log.debug("-------------------------------------------------------------------------------------------------------------");
    }

}
